<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addOneTodo="addOneTodo" :todos="todos"></Header>
      <Main
        :todos="todos"
        :updataTodo="updataTodo"
        :deleteOneTodo="deleteOneTodo"
      ></Main>
      <Footer
        :todos="todos"
        :updateAllTodo="updateAllTodo"
        :deleteAll="deleteAll"
      ></Footer>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header/index.vue";
import Main from "@/components/Main/index.vue";
import Footer from "@/components/Footer/index.vue";
export default {
  name: "App",
  components: {
    Header,
    Main,
    Footer,
  },
  //item中的数据
  data() {
    return {
      // 拿到之前存在本地的数据，或空数组是为了最初数组为空不报错
      todos: JSON.parse(localStorage.getItem("todos")) || [],
    };
  },
  methods: {
    // 新增todo
    addOneTodo(todo) {
      this.todos.unshift(todo); //子组件调用时需要调用一个参数
    },
    // 修改单个按钮选中的状态
    updataTodo(index) {
      this.todos[index].isOver = !this.todos[index].isOver;
    },
    // 删除单个按钮
    // 因为子组件要改父组件的数据，子组件调用时需要传递一个参数
    deleteOneTodo(index) {
      this.todos.splice(index, 1);
    },
    // 修改所有数据的选中状态
    updateAllTodo(vlaue) {
      this.todos.forEach((item) => {
        item.isOver = vlaue;
      });
    },
    // 删除已完成任务
    deleteAll() {
      this.todos = this.todos.filter((item) => {
        return !item.isOver;
      });
    },
  },
  // 将数据存储在本地
  watch: {
    todos: {
      handler(newVal, oldVal) {
        localStorage.setItem("todos", JSON.stringify(newVal));
      },
      deep: true, //开启深度监视
    },
  },
};
</script>

<style scoped>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
